﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.ReturnOrder;
using ProTrack.Report;
using ProTrack.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 采购退货
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class OrderPoReturnController : ControllerBase
    {
        /// <summary>
        /// 采购退货接口
        /// </summary>
        public IOrderPoReturnServices Services { get; }
        public LogHelper LogHelper { get; }

        public OrderPoReturnController(IOrderPoReturnServices services, LogHelper logHelper)
        {
            Services = services;
            LogHelper = logHelper;
        }
        
        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购单-获取所有", ex, HttpContext);
            }
            return Ok(status);
        }
        
        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="Number"></param>
        /// <param name="VendorId"></param>
        /// <param name="WarehouseId"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string Number, [FromQuery] string VendorId, [FromQuery] string WarehouseId, [FromQuery] string Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                Number = Number ?? "";
                VendorId = VendorId ?? "";
                WarehouseId = WarehouseId ?? ""; 
                Status = Status ?? "";
                var list = await Services.GetAsync(PageIndex, PageSize, Number, VendorId, WarehouseId, Status);
                status.Data = list;
                status.Count = await Services.GetCountAsync(Number, VendorId, WarehouseId, Status);
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购单-分页获取", ex, HttpContext);
            }
            return Ok(status);
        }

        [HttpGet("GetOrderPoReturnId")]
        public async Task<IActionResult> GetOrderPoReturnId([FromQuery] string Id, [FromQuery] string WarehouseId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {

                var list = await Services.GetOrderPoReturnId(Id, WarehouseId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购退货-获取商品", ex, HttpContext);
            }

            return Ok(status);
        }
        /// <summary>
        /// 条件查询“采购退货”数据
        /// </summary>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="Number"></param>
        /// <param name="VendorId"></param>
        /// <param name="WarehouseId"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        [HttpGet("GetWhPoInboundsj")]
        public async Task<IActionResult> GetWhPoInboundsj([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string Number, [FromQuery] string VendorId, [FromQuery] string WarehouseId, [FromQuery] string Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                Number = Number ?? "";
                VendorId = VendorId ?? "";
                WarehouseId = WarehouseId ?? "";
                Status = Status ?? "";

                var list = await Services.GetAsyncWhPoInbound(PageIndex, PageSize, Number, VendorId, WarehouseId, Status);
                status.Data = list;
                status.Count = await Services.GetCountWhPoInbound(Number, VendorId, WarehouseId, Status);
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购退货-分页获取", ex, HttpContext);
            }

            return Ok(status);
        }
        /// <summary>
        /// 新增采购退货
        /// </summary>
        /// <param name="model">规格模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] OrderPoReturn model, [FromForm] string OrderPoReturnItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OrderPoReturnItem> list = new List<OrderPoReturnItem>();
            try
            {
                if (!string.IsNullOrEmpty(OrderPoReturnItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OrderPoReturnItem>>(OrderPoReturnItemString);
                    list.ForEach(x => {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        //主表Id由于是自增，由内部方法自动赋值,无需手动介入
                    });
                }
                model.CreateTime = StringHelper.GetTimeNow();
                model.Creator = User.Identity.Name;

                var isSuccess = await Services.AddAsync(model, list);
                if (isSuccess)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("客户退货单-新增", ex, HttpContext);
            }

            return Ok(status);
        }
        /// <summary>
        /// 单个删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status  = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.DeleteAsync(Id);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购单-删除", ex, HttpContext);
            }
            return Ok(status);
        }

        [HttpPut]
        public async Task<IActionResult> Update([FromForm] OrderPoReturn model, [FromForm] string OrderPoReturnItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OrderPoReturnItem> list = new List<OrderPoReturnItem>();
            try
            {
                if (!string.IsNullOrEmpty(OrderPoReturnItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OrderPoReturnItem>>(OrderPoReturnItemString);
                    list.ForEach(x =>
                    {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        x.OrderPoReturnId = model.Id;

                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = User.Identity.Name;
                var isSuccess = await Services.UpdateAsync(model, list);
                if (isSuccess)
                {
                    status.Msg = "修改成功";

                    //操作日志
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据。";
                }

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "编辑失败，请检查已出库的物料产品数量是否充足！编辑单据自动还原原始单据的物料产品数量。";
                //写日志
                await LogHelper.WriteErrorLog("采购退货-修改", ex, HttpContext);
            }

            return Ok(status);
        }
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("采购单-批量删除", ex, HttpContext);
            }
            return Ok(status);
        }
        /// <summary>
        /// 导出数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("Export")]
        public async Task<IActionResult> Export()
        {
            try
            {

                var list = await Services.GetAllAsync();
                var TitleArray = new ReportDomain[] {
                    new ReportDomain{ Title="序号",Fileld="No"},
                    new ReportDomain{ Title="单号",Fileld="Number"},
                    new ReportDomain{ Title="供应商",Fileld="VendorName"},
                    new ReportDomain{ Title="联系人",Fileld="VendorContact"},
                    new ReportDomain{ Title="联系人电话",Fileld="VendorContactTel"},
                    new ReportDomain{ Title="收款方式",Fileld="PaymentCategory"},
                    new ReportDomain{ Title="收款账户",Fileld="PaymentAccount"},
                    new ReportDomain{ Title="收款日期",Fileld="PaymentTime"},
                    new ReportDomain{ Title="出货仓",Fileld="WarehouseName"},
                    new ReportDomain{ Title="退货日期",Fileld="ReturnDate"},
                    new ReportDomain{ Title="出库日期",Fileld="DeliveryDate"},
                    new ReportDomain{ Title="备注",Fileld="Remark"},
                    new ReportDomain{ Title="状态",Fileld="Status"},
                };
                var fileArray = BaseReport.Export(list, "采购退货信息", TitleArray);

                return File(new System.IO.MemoryStream(fileArray), "application/octet-stream", "采购退货信息.xls");
            }
            catch (Exception ex)
            {

                //此处应当日志记录
                await LogHelper.WriteErrorLog("采购退货-导出", ex, HttpContext);
                return new JsonResult(BaseStatus.CreateInstance(-1, "导出失败，服务器异常请稍后再试！"));
            }

        }
    }
}
